package controller;

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import model.AppModel;
import view.AppView;

/**
 * The application controller that controls everything
 * @author MUSAB
 */
public class AppController{

	/**
	 * The application model
	 */
	protected AppModel model;
	
	/**
	 * The application view
	 */
	protected AppView view;

	
	/**
	 * Constructor for controller.
	 * 
	 * The controller has direct access to the model and view
	 * @param view2 
	 * @param model2 
	 * @param model The application model
	 */
	public AppController(AppModel model, AppView view) {
		this.model = model;
		this.view = view;
		init();
	}

	/**
	 * Begin the application
	 */
	public void init(){
		
		// Tell the model to init the DAO
		model.initDao();
		
		// Init controllers
		new ListingController(model, view);
		new MenuController(model, view);
		new NavigationController(model, view);
		new PreviewController(model, view);
		
		loadUser();
	}
	
	/**
	 * Try to load the user
	 */
	private void loadUser(){
		
		String username = JOptionPane.showInputDialog("Enter your username:");
		if (username == null){
			System.exit(0);
		}
		
		// Sanitize username
		username = username.toLowerCase().trim();
		
		while(username.equals("")){
			username = JOptionPane.showInputDialog("Empty input, please enter a valid username:");
			username = username.toLowerCase().trim();
		}
		
		// Try to load that user
		if (model.loadAccount(username) == true){
			view.init();
		} else {
			if (JOptionPane.showConfirmDialog(null, "Could not locate your account, create a new one with username: " + username + "?", "WARNING",JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {

				// Create new account for this user...
				model.createAccount(username);
				
				view.init();
			} else {
				System.exit(0);
			}
		}
	}
	

}
